package com.controller;

import com.bean.Msg;
import com.bean.User;
import com.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 注册的controller
 * @author WxrStart
 * @create 2022-05-17 13:28
 */
@Controller
@Slf4j
public class RegistController {
    @Autowired
    IUserService iUserService;

    /**
     *注册新用户，并且进行JSR-303校验
     * @param user 前台传过来的email和password封装成了一个User对象
     * @param result JRS-303错误
     * @return
     */
    @PostMapping("/regist")
    @ResponseBody
    public Msg registUser(@RequestBody @Valid User user, BindingResult result){
        //jsr303校验
        if (result.hasErrors()) {
            Map<String,Object> map=new HashMap();
            //校验失败，返回错误信息给前端
            List<FieldError> errors = result.getFieldErrors();
            for(FieldError fieldErrors:errors ){
                map.put(fieldErrors.getField(), fieldErrors.getDefaultMessage());
            }
            Msg errorFields = Msg.fail().add("errorFields", map);
            return errorFields;
        } else {
            //进行注册
            Integer integer = iUserService.addUser(user);
                return Msg.success().add("result", "您已成功注册");
        }
    }


}
